<!-- 多柱子柱状图 -->
<template>
  <div class="w-100 h-100">
    <fakeLenfend
      :color="colors.slice(0, props.legendLabel.length)"
      :text="legendLabel"
    >
    </fakeLenfend>

    <div class="w-100" style="height: 90%" :id="echartsId + 'div'">
      <div
        :id="echartsId"
        class="w-100"
        style="height: 100%; position: relative"
      ></div>
    </div>
  </div>
</template>

<script setup lang="ts">
import fakeLenfend from "@/components/project/fakeLegend.vue";
import * as echarts from "echarts";
import { useConvert } from "@/hook/useConvert";
const props = defineProps({
  echartsData: {
    type: Array,
    default: () => [],
  },
  echartsId: {
    type: String,
    default: "",
  },
  derection: {
    type: String,
    default: "",
  },
  barWidth: {
    type: String,
    default: "60%",
  },
  xlabel: {
    type: Array,
    default: () => [],
  },
  legendLabel: {
    type: Array<string>,
    default: () => [],
  },
  colors: {
    type: Array<string>,
    default: [
      "rgba(3, 230, 254, 1)",
      "rgba(184, 235, 143, 1)",
      "rgba(251, 216, 160, 1)",
    ],
  },
  unit: {
    type: String,
    default: "个",
  },
  mouseShowLabel: {
    type: Boolean,
    default: true,
  },
});

let option_h = {
  grid: {
    containLabel: true, // 确保标签被完整显示
  },
  tooltip: {
    show: true, // 鼠标悬停时显示 tooltip
  },
  xAxis: {
    type: "value", // 将值轴配置到X轴
    axisLabel: {
      interval: 0,
      formatter: "{value}" + props.unit,
      fontSize: 20,
      fontFamily: "OPPOSans-Regular",
    },
    nameTextStyle: {
      color: "#DEDEDE",
      fontSize: 20,
      padding: 10,
    },
    splitLine: {
      show: true,
      lineStyle: {
        opacity: 0.2,
      },
    },
  },
  yAxis: {
    type: "category", // 将类别轴配置到Y轴
    data: props.echartsData.map((item: any) => item.name),
    axisLabel: {
      interval: 0,
      fontSize: 20,
      fontFamily: "OPPOSans-Regular",
      color: "#fff",
    },
  },
};
let option_v = {
  tooltip: {
    show: true, // 鼠标悬停时显示 tooltip
  },
  grid: {
    containLabel: true, // 确保标签被完整显示
  },
  yAxis: {
    type: "value",
    axisLabel: {
      formatter: "{value}" + props.unit,
      fontSize: 20,
      interval: 0,
      fontFamily: "OPPOSans-Regular",
    },
    nameTextStyle: {
      color: "#DEDEDE",
      fontSize: 20,
      padding: 10,
    },

    splitLine: {
      show: true,
      lineStyle: {
        type: "dashed", //线的类型 虚线0
        opacity: 0.2, //透明度
      },
    },
  },
  xAxis: {
    type: "category",
    data: useConvert().flattenArray(props.xlabel),
    axisLabel: {
      interval: 0,

      fontSize: 20,
      fontFamily: "OPPOSans-Regular",
    },
  },
};
let myChart: any = null;

const removeAlpha = (color: string): string => {
  const regex =
    /rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*([01]?(\.\d+)?)\s*\)/g;
  return color
    ? color.replace(regex, "rgb($1, $2, $3,0)")
    : "rgba(3, 230, 254, 0)";
};
onMounted(() => {
  let optionDetection: any = {};
  props.derection === "v"
    ? (optionDetection = option_h)
    : (optionDetection = option_v);
  optionDetection.series = [];

  let seriesData = {
    type: "bar",
    data: Array.from((props.echartsData[0] as any).value),
    itemStyle: {
      color: function (params: any) {
        
        let color =props.colors[splitData(params.dataIndex, Array.from(props.xlabel))];
        return new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          {
            offset: 0,
            color: color, // 顶部颜色
          },
          {
            offset: 0.01,
            color: removeAlpha(color), // 接近底部的颜色
          },
          {
            offset: 1,
            color: color, // 底部颜色，透明
          },
        ]);
      },
    },
  };
  optionDetection.series = seriesData;
  console.log(optionDetection, "xlabel");

  myChart = echarts.init(
    document.getElementById(props.echartsId) as HTMLElement
  );
  myChart.setOption(optionDetection);

  var divElement = document.getElementById(props.echartsId + "div");
  if (props.mouseShowLabel) {
    // 添加鼠标移入事件监听器
    (divElement as any).addEventListener("mouseover", function (event: any) {
      var option = myChart.getOption();
      option.series.forEach(function (serie: any) {
        serie.label.show = true;
      });
      myChart.setOption(option);
      // 这里可以添加你想要执行的逻辑
    });
    (divElement as any).addEventListener("mouseout", function (event: any) {
      var option = myChart.getOption();
      option.series.forEach(function (serie: any) {
        serie.label.show = false;
      });
      myChart.setOption(option);
      // 这里可以添加你想要执行的逻辑
    });
  }
});
// 拆分数组
//   const splitData=(input: string[][], values: number[]): number[][] =>{
//     let result: number[][] = [];
//     let index = 0; // 用于遍历 values 数组的索引

//     // 遍历输入的嵌套数组
//     input.forEach(group => {
//         let groupValues: number[] = [];

//         // 遍历每个分组内的元素，并根据 values 数组来拆分
//         group.forEach(() => {
//             groupValues.push(values[index]);
//             index++;
//         });

//         result.push(groupValues);
//     });

//     return result;
// }

//查找索引
const splitData = (index: number, values: any[]): number => {
  let result: number;

  let arr = useConvert().flattenArray(values);
  console.log(findArrayIndex(arr[index], values), "fdmnskfms");
  result = findArrayIndex(arr[index], values);
  return result;
};
const findArrayIndex = (value: string, data: string[][]): number => {
  for (let i = 0; i < data.length; i++) {
    const subArray = data[i];
    if (subArray.includes(value)) {
      return i;
    }
  }
  return -1; // 如果未找到，返回 -1
};

onBeforeUnmount(() => {
  // 销毁 ECharts 实例
  if (myChart) {
    myChart.dispose();
  }
});
</script>

<style></style>
